package com.qf.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器， 在未登录之前，不可以访问 具体的业务
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化登录过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        if("/login.html".equalsIgnoreCase(requestURI) ||"/createCode".equalsIgnoreCase(requestURI) || "/login".equalsIgnoreCase(requestURI) || "/error.jsp".equalsIgnoreCase(requestURI)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否已经登录
        //从session中获取 manager对象， 如果获取到了， 则登录了， 否则没有登录
        HttpSession session = request.getSession();
        Object manager = session.getAttribute("manager");
        if(manager == null) {
            response.sendRedirect("/login.html");
        }else {
            //不为null， 说明已登录，放行
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("销毁登录过滤器");
    }
}
